package edu.zjut.sjq.service;

import edu.zjut.sjq.bean.Article;
import edu.zjut.sjq.bean.Grade;
import edu.zjut.sjq.bean.Result;
import edu.zjut.sjq.bean.User;
import edu.zjut.sjq.mapper.ArticleMapper;
import edu.zjut.sjq.mapper.GradeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Created by sue on 2017/3/18.
 */
@Service
public class GradeService {
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private HttpSession session;

    // 评分
    public Result addGrade(Grade grade){
        Result result=new Result();
        result.setRes(0);
        User user = (User) session.getAttribute("user");
        if (gradeMapper.selectByUserIdAndArticleId(user.getId(),grade.getArticleId())==null){
            if (articleMapper.getArticleById(grade.getArticleId(),user.getId()).getTag()==1){
                result.setMsg("该作品不在评分状态!");
            }else {
                grade.setCreateTime(new Date());
                grade.setUserId(user.getId());
                Integer res=gradeMapper.insert(grade);
                result.setRes(res);
                if (res==1)
                    result.setMsg("评分成功");
                else
                    result.setMsg("保存失败");
            }
        }else {
            result.setMsg("您已经评分了该作品！");
        }
        return result;
    }

    // 删除评分
    public Result deleteGrade(Integer articleId){
        Result result=new Result();
        result.setRes(0);
        User user = (User) session.getAttribute("user");
        Integer res = gradeMapper.deleteByUserIdAndArticleId(user.getId(), articleId);
        result.setRes(res);
        if (res==1)
            result.setMsg("删除成功");
        else
            result.setMsg("记录不存在");
        return result;

    }

    // 获取该作品的所有评分
    public List<Grade> getAllGrade(Integer articleId){
        return gradeMapper.selectByArticleId(articleId);
    }

    // 统计平均分
    public Number countGradeAvg(Integer articleId) throws ParseException {
        List<Grade> gradeList=gradeMapper.selectByArticleId(articleId);
        Number res=0.00;
        if (gradeList.size()==0){
            gradeMapper.updateGradeAvgForArticle(articleId,res);
            return res;
        }

        double count=0;
        for (Grade temp : gradeList){
            if (temp.getResult()!=null)
                count+=(double)temp.getResult();
        }
        DecimalFormat decimalFormat =new DecimalFormat("0.00");
        String format = decimalFormat.format(count / gradeList.size());
        res = decimalFormat.parse(format);
        // 更新
        gradeMapper.updateGradeAvgForArticle(articleId,res);
        return res;
    }
}
